package com.tlgen.orm.utils.xml;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.StringReader;
import java.util.*;

@Slf4j
public class SqlXmlParser {

    /**
     * 从XML内容中提取指定ID的SQL内容
     *
     * @param xmlContent XML内容字符串
     * @param sqlId 要查找的SQL ID
     * @return 匹配的SQL内容（包含动态标签）
     * @throws DocumentException 如果XML解析失败
     * @throws IllegalArgumentException 如果找不到指定ID的SQL
     */
    public static String getSqlContentById(String xmlContent, String sqlId) throws DocumentException {
        // 包裹多根节点
        String wrappedXml = "<root>" + xmlContent + "</root>";
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(wrappedXml));
        Element root = document.getRootElement();

        // 遍历所有SQL块
        for (Object sqlsObj : root.elements("sqls")) {
            Element sqls = (Element) sqlsObj;

            // 遍历所有SQL元素
            for (Object elementObj : sqls.elements()) {
                Element element = (Element) elementObj;
                String tagName = element.getName();

                if (isSqlElement(tagName)) {
                    String id = element.attributeValue("id");
                    if (sqlId.equals(id)) {
                        return extractSqlContent(element);
                    }
                }
            }
        }

        return "";
    }

    private static boolean isSqlElement(String tagName) {
        return "select".equals(tagName) || "insert".equals(tagName) ||
                "update".equals(tagName) || "delete".equals(tagName);
    }

    private static String extractSqlContent(Element element) {
        StringBuilder content = new StringBuilder();
        for (Object nodeObj : element.content()) {
            if (nodeObj instanceof org.dom4j.Text) {
                content.append(((org.dom4j.Text) nodeObj).getText());
            } else if (nodeObj instanceof Element) {
                Element child = (Element) nodeObj;
                content.append(child.asXML());
            }
        }
        return content.toString();
    }

    /**
     * 从XML内容中提取所有SQL ID列表
     *
     * @param xmlContent XML内容字符串
     * @return SQL ID列表
     * @throws DocumentException 如果XML解析失败
     */
    public static List<String> getAllSqlIds(String xmlContent) throws DocumentException {
        List<String> ids = new ArrayList<>();

        // 包裹多根节点
        String wrappedXml = "<root>" + xmlContent + "</root>";
        SAXReader reader = new SAXReader();
        Document document = reader.read(new StringReader(wrappedXml));
        Element root = document.getRootElement();

        // 遍历所有SQL块
        for (Object sqlsObj : root.elements("sqls")) {
            Element sqls = (Element) sqlsObj;

            // 遍历所有SQL元素
            for (Object elementObj : sqls.elements()) {
                Element element = (Element) elementObj;
                String tagName = element.getName();

                if (isSqlElement(tagName)) {
                    String id = element.attributeValue("id");
                    if (id != null && !id.isEmpty()) {
                        ids.add(id);
                    }
                }
            }
        }

        return ids;
    }
}